package com.banciyuan.bcywebview.biz.goods.order.confirmorder;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.ZhipinApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.helper.ActionbarHelper;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.biz.goods.address.ReceiverAddressHelper;
import com.banciyuan.bcywebview.biz.goods.order.myorder.MyOrderActivity;
import com.banciyuan.bcywebview.biz.goods.shoppingcart.ShoppingCartHelper;
import com.banciyuan.bcywebview.utils.currency.CurrencyUtil;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.pingplusplus.android.Pingpp;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.daoexample.model.Order;
import de.greenrobot.daoexample.model.OrderAddress;


public class ConfirmOrderActivity extends BaseActivity implements View.OnClickListener {
    public static final int CONFIRMORDER = 99;
    public static final int SHOPPINGCART_TYPE = 0;
    public static final int COMMON_TYPE = 1;
    private int type = COMMON_TYPE;
    private RecyclerView mRecyclerView;
    private View viewProgressOrder;
    public static final int GOADD_ADDRESS = 100;
    private ConfirmOrderAdapter confirmOrderAdapter;
    private List<Order> mDetailGoodsList;
    private String uid;
    private String cartId;
    private RequestQueue mQueue;
    private String charge;
    private String sn;
    private String allSum;
    private TextView tvTotalPrice;
    private View viewGotoOrder;
    private int requestCount = 0;
    private ProgressbarHelper mProgressbarHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.confirmorder_layout);
        initArgs();
        initActionbar();
        initUi();
        initProgressbar();
        initAction();
        initData();
    }

    @Override
    protected void initArgs() {
        uid = UserDataHelper.getInstance(this).getUid();
        Intent intent = getIntent();
        cartId = intent.getStringExtra(gotoUtil.INTENT_VALUE_ONE);
        type = intent.getIntExtra(gotoUtil.INTENT_VALUE_TWO, COMMON_TYPE);
        mQueue = VolleyQueue.getRquest(this);
    }

    @Override
    protected void initProgressbar() {
        View mProgressbarView = findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initActionbar() {
        ActionbarHelper mActionbarHelper = new ActionbarHelper(this, findViewById(R.id.base_action_bar));
        mActionbarHelper.setTitle(getString(R.string.confirm_order));
    }

    @Override
    protected void initUi() {
        tvTotalPrice = (TextView) findViewById(R.id.tv_total_price);
        viewGotoOrder = findViewById(R.id.tv_go_order);
        viewGotoOrder.setBackgroundColor(getResources().getColor(R.color.pink));
        viewProgressOrder = findViewById(R.id.view_progress_order);
        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, RecyclerView.VERTICAL, false);
        mRecyclerView.setLayoutManager(linearLayoutManager);
    }

    @Override
    protected void initAction() {
        viewGotoOrder.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        List<BcyPair> paramsList = new ArrayList<>();
        paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(this).getToken()));
        paramsList.add(new BcyPair(HttpUtils.CART_ID, cartId));
        HashMap<String, String> params = HttpUtils.getData(paramsList);
        String url = HttpUtils.BASE_URL + ZhipinApi.showConfirmOrder();
        Response.Listener succ = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    if (StatusCodeUtils.dealStatusCode(s, ConfirmOrderActivity.this)) {
                        JSONObject result = new JSONObject(s);
                        JSONObject jsonObject = result.getJSONObject(HttpUtils.UPLOAD_DATA);
                        allSum = jsonObject.getString("all_sum");
                        mDetailGoodsList = new Gson().fromJson(jsonObject.getString("goods"), new TypeToken<List<Order>>() {
                        }.getType());
                        processData();
                        mProgressbarHelper.onSuccess();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    mProgressbarHelper.onFailed();
                }
            }
        };

        Response.ErrorListener error = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                mProgressbarHelper.onFailed();
            }
        };
        OnErrorProxy errorProxy = new OnErrorProxy(error, succ, url, this, params);
        StringRequestParam stringRequest = new StringRequestParam(Request.Method.POST, url, params, succ, errorProxy);
        mQueue.add(stringRequest);
    }

    private void processData() {
        tvTotalPrice.setText(String.format(getString(R.string.total_price_format), CurrencyUtil.getMoney(allSum)));
        confirmOrderAdapter = new ConfirmOrderAdapter(this, mDetailGoodsList);
        mRecyclerView.setAdapter(confirmOrderAdapter);
    }

    private void checkOrderStatus() {
        requestCount++;
        List<BcyPair> paramsList = new ArrayList<>();
        paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(this).getToken()));
        paramsList.add(new BcyPair(HttpUtils.SN, sn));
        HashMap<String, String> params = HttpUtils.getData(paramsList);
        String url = HttpUtils.BASE_URL + ZhipinApi.getOrderStatus();
        Response.Listener succ = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject result = new JSONObject(response);
                    int status = result.getInt(HttpUtils.UPLOAD_STATUS);
                    if (status == 1) {
                        gotoOrderActivity();
                    } else {
                        if (requestCount >= 3) {
                            gotoOrderActivity();
                        } else {
                            checkOrderStatusAgain();
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    onError();
                }
            }
        };
        Response.ErrorListener error = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                onError();
            }
        };

        OnErrorProxy errorProxy = new OnErrorProxy(error, succ, url, this, params);
        StringRequestParam stringRequest = new StringRequestParam(Request.Method.POST, url, params, succ, errorProxy);
        mQueue.add(stringRequest);
    }

    private void checkOrderStatusAgain() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                checkOrderStatus();
            }
        }, 5000);
    }

    private void gotoOrderActivity() {
        gotoUtil.gotoAct(ConfirmOrderActivity.this, MyOrderActivity.class);
        finish();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_go_order:
                OrderAddress address = new OrderAddress();
                if (setAddress(address)) {
                    viewProgressOrder.setVisibility(View.VISIBLE);
                    viewGotoOrder.setClickable(false);
                    viewGotoOrder.setBackgroundColor(getResources().getColor(R.color.grey_ten_level));
                    createOrder(new Gson().toJson(address));
                } else
                    MyToast.show(this, getString(R.string.input_correct_address));
                break;
        }
    }

    private boolean setAddress(OrderAddress address) {
        if (setReceiverName(address)) return false;
        if (setReceiverPhone(address)) return false;
        if (setReceiverDetailAddress(address)) return false;
        if (setReceiverCityCode(address)) return false;
        if (setReceiverProvinceCode(address)) return false;
        return true;
    }

    private boolean setReceiverProvinceCode(OrderAddress address) {
        String receiverProvinceCode = ReceiverAddressHelper.getReceiverProvinceCode(this, uid);
        if (!TextUtils.isEmpty(receiverProvinceCode))
            address.setArea_province(receiverProvinceCode);
        else
            return true;
        return false;
    }

    private boolean setReceiverCityCode(OrderAddress address) {
        String receiverCityCode = ReceiverAddressHelper.getReceiverCityCode(this, uid);
        if (!TextUtils.isEmpty(receiverCityCode))
            address.setArea_city(receiverCityCode);
        else
            return true;
        return false;
    }

    private boolean setReceiverDetailAddress(OrderAddress address) {
        String receiverDetailAddress = ReceiverAddressHelper.getReceiverDetailAddress(this, uid);
        if (!TextUtils.isEmpty(receiverDetailAddress))
            address.setAddress(receiverDetailAddress);
        else
            return true;
        return false;
    }

    private boolean setReceiverPhone(OrderAddress address) {
        String receiverPhone = ReceiverAddressHelper.getReceiverPhone(this, uid);
        if (!TextUtils.isEmpty(receiverPhone))
            address.setMobile(receiverPhone);
        else
            return true;
        return false;
    }

    private boolean setReceiverName(OrderAddress address) {
        String receiverName = ReceiverAddressHelper.getReceiverName(this, uid);
        if (!TextUtils.isEmpty(receiverName))
            address.setName(receiverName);
        else
            return true;
        return false;
    }

    private void createOrder(String addressData) {
        List<BcyPair> paramsList = new ArrayList<>();
        paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(this).getToken()));
        paramsList.add(new BcyPair(HttpUtils.CART_ID, cartId));
        paramsList.add(new BcyPair(HttpUtils.ADDRESS, addressData));
        HashMap<String, String> params = HttpUtils.getData(paramsList);
        String url = HttpUtils.BASE_URL + ZhipinApi.createOrder();
        Response.Listener succ = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    if (StatusCodeUtils.dealStatusCode(response, ConfirmOrderActivity.this)) {
                        JSONObject jsonobject = new JSONObject(response);
                        JSONObject result = jsonobject.getJSONObject(HttpUtils.UPLOAD_DATA);
                        charge = result.getString("charge");
                        sn = result.getString("sn");
                        Pingpp.createPayment(ConfirmOrderActivity.this, charge);
                        deleteOrderedItems();
                    } else {
                        viewGotoOrder.setClickable(true);
                        viewGotoOrder.setBackgroundColor(getResources().getColor(R.color.pink));
                        viewProgressOrder.setVisibility(View.GONE);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    onError();
                }
            }
        };

        Response.ErrorListener error = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                onError();
            }
        };
        OnErrorProxy errorProxy = new OnErrorProxy(error, succ, url, this, params);
        StringRequestParam stringRequest = new StringRequestParam(Request.Method.POST, url, params, succ, errorProxy);
        mQueue.add(stringRequest);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == GOADD_ADDRESS) {
            confirmOrderAdapter.notifyItemChanged(0);
        } else if (requestCode == Pingpp.REQUEST_CODE_PAYMENT) {
            if (resultCode == Activity.RESULT_OK) {
                String result = data.getExtras().getString("pay_result");
                if (result.equals("success")) {
                    checkOrderStatus();
                } else if (result.equals("fail")) {
                    MyToast.show(this, getString(R.string.pay_fail));
                    viewProgressOrder.setVisibility(View.GONE);
                    gotoOrderActivity();
                } else if (result.equals("cancel")) {
                    MyToast.show(this, getString(R.string.cancel_pay));
                    viewProgressOrder.setVisibility(View.GONE);
                    gotoOrderActivity();
                }
            }
        }
    }

    private void deleteOrderedItems() {
        if (type == SHOPPINGCART_TYPE)
            ShoppingCartHelper.deleteMutilOrderItem(ConfirmOrderActivity.this, mDetailGoodsList);
    }

    private void onError() {
        viewProgressOrder.setVisibility(View.GONE);
        MyToast.show(this, getString(R.string.order_failed));
    }

    @Override
    public void onBackPressed() {
        if (!viewProgressOrder.isShown())
            super.onBackPressed();
    }
}
